package com.course.app.transformer;

import com.course.app.api.data.MarkDTO;
import com.course.app.api.data.MarkItemDTO;
import com.course.constant.MarkTitle;
import com.course.domain.model.ClassMark;
import com.course.domain.model.ClassPlan;
import com.course.domain.model.TaskClass;
import com.course.domain.model.Teacher;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;

import java.util.Date;
import java.util.List;

/**
 * Created by Justin on 2017/5/30.
 */
public class MarkTransformer {

    public static MarkDTO toDTO(List<MarkItemDTO> items, Page<ClassPlan> page) {
        MarkDTO markDTO = new MarkDTO();
        markDTO.setItems(items);
        if (page != null) {
            markDTO.setTotalPages(page.getTotalPages());
            markDTO.setTotalItems(page.getTotalElements());
            markDTO.setPageSize(page.getSize());
            markDTO.setPageNumber(page.getNumber());
            markDTO.setItemNumber(page.getNumberOfElements());
            markDTO.setFirst(page.isFirst());
            markDTO.setLast(page.isLast());
        }
        return markDTO;
    }

    public static MarkItemDTO toItem(ClassPlan plan, Teacher teacher, TaskClass task) {
        MarkItemDTO itemDTO = new MarkItemDTO();
        itemDTO.setId(plan.getId());
        itemDTO.setClassId(plan.getClassId());
        itemDTO.setTeacherId(teacher.getId());
        itemDTO.setClassTitle(task.getTitle());
        itemDTO.setTeacherName(teacher.getName());
        Gson gson = new Gson();
        ClassMark mark = gson.fromJson(plan.getMark(), ClassMark.class);
        itemDTO.setDate(toDate(plan.getDate()));
        itemDTO.setTitles(MarkTitle.TITLES);
        itemDTO.setValues(toValue(mark));
        return itemDTO;
    }

    private static String[] toValue(ClassMark mark) {
        String mark1 = String.valueOf(mark.getMark1());
        String mark2 = String.valueOf(mark.getMark2());
        String mark3 = String.valueOf(mark.getMark3());
        String suggest = mark.getSuggest();
        String comment = mark.getComment();
        String sugCn = mark.getSugCn();
        String comCn = mark.getComCn();
        suggest = suggest != null ? suggest : "";
        comment = comment != null ? comment : "";
        sugCn = StringUtils.isNoneBlank(sugCn) ? sugCn : suggest;
        comCn = StringUtils.isNoneBlank(comCn) ? comCn : comment;

        return new String[]{mark1, mark2, mark3, sugCn, comCn};
    }

    private static Date toDate(Date date) {
        return date;
    }
}
